import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

import '../../../API/user/user.dart';
import '../../../data/profile_data.dart';

class UpdateAvatarPage extends StatefulWidget {
  const UpdateAvatarPage({super.key});

  @override
  UpdateAvatarPageState createState() => UpdateAvatarPageState();
}

class UpdateAvatarPageState extends State<UpdateAvatarPage> {
  final userController = Get.find<UserController>();
  // 用于存储头像图片
  File? _image;
  // 图片选择器
  final ImagePicker _picker = ImagePicker();

  Future<void> _onSave(File imageFile) async {
    final response = await ApiService.updateAvatar(imageFile);
    if (kDebugMode) {
      print(response);
    }
    if (response['code'] == 20031) {
      Get.back();//先back再提示,不然back会把提示关掉但不回到上一页
      Get.snackbar("", "更改成功",
          snackPosition: SnackPosition.TOP,
          duration: const Duration(seconds: 2)); // 显示提示信息
          userController.getUserInfo();//更新用户信息
    } else if(response['code'] == 20030) {
      Get.snackbar("错误", "更改错误:${response['message']}",
          duration: const Duration(seconds: 4),
          snackPosition: SnackPosition.TOP); // 显示错误信息
    }
    else if(response['code'] == 30010) {
      Get.snackbar("错误", "格式错误:${response['message']}",
          duration: const Duration(seconds: 4),
          snackPosition: SnackPosition.TOP); // 显示错误信息
    }
  }

  // 从相册选择图片
  Future<void> _pickImageFromGallery() async {
    final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
      });
    }
  }

  // 从相机拍摄图片
  Future<void> _pickImageFromCamera() async {
    final pickedFile = await _picker.pickImage(source: ImageSource.camera);
    if (pickedFile != null) {
      setState(() {
        _image = File(pickedFile.path);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("修改头像"),
        actions: [
          // 保存按钮
          TextButton(
            onPressed: () {
              // 在这里实现保存头像的逻辑
              if (_image != null) {
                // 上传或保存头像
                _onSave(_image!);
              } else {
                // 提示用户选择头像
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text("请选择头像")),
                );
              }
            },
            child: Text(
              "保存",
              style: TextStyle(color: Colors.black, fontSize: 19),
            ),
          ),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 头像显示区域
            CircleAvatar(
              radius: 60,
              backgroundImage: _image != null ? FileImage(_image!) : CachedNetworkImageProvider(userController.pictureUrl.value),
              // child: _image == null
              //     ? Icon(
              //   Icons.person,
              //   size: 60,
              //   color: Colors.grey,
              // )
              //     : null,
            ),
            SizedBox(height: 20),
            // 选择头像按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 从相册选择
                ElevatedButton.icon(
                  icon: Icon(Icons.photo_library),
                  label: Text("从相册选择"),
                  onPressed: _pickImageFromGallery,
                ),
                SizedBox(width: 20),
                // 从相机拍摄
                ElevatedButton.icon(
                  icon: Icon(Icons.camera_alt),
                  label: Text("拍照"),
                  onPressed: _pickImageFromCamera,
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}